/*
 *  Peripherals.c
 *
 *
 *  Created by Akito van Troyer on 11/21/10.
 *  Copyright 2010 Akito van Troyer. All rights reserved.
 *
 */

#include "Peripherals.h"
#include "Debug_LED.h"

void init_spi (void);

void setupPeripherals(void){
	InitClock();
	initLED();
	InitIO();
	InitADC();
	InitPWM();
//	init_spi();
}

void InitClock(void){
   cli();
	CLKPR = (1 << CLKPCE);
	CLKPR = 0x00;
	sei();
}

void InitIO(void){
	//Outputs
	sbi(LEDR_DDR, LEDR_PINNUM);
	sbi(LEDG_DDR, LEDG_PINNUM);
    sbi(LEDB_DDR, LEDB_PINNUM);
	sbi(IRLED_DDR, IRLED_PINNUM);
    sbi(SPK_DDR,SPK_PINNUM);
    sbi(MISO_DDR,MISO_PINNUM);
    sbi(CS_DDR,CS_PINNUM);
    sbi(SCK_DDR,SCK_PINNUM);

    //Inputs
    cbi(MOSI_DDR,MOSI_PINNUM);
    sbi(MOSI_PORT,MOSI_PINNUM);
}

void InitPWM(void){
//----------- Start Audio shit ------------
    //Audio playback setup (timer 2)
//    TCCR1A = 0b10110011;

//	  TCCR1A = 0b10100011;
//    TCCR1B = 0b00000010;


    // ramp(1);

    //Set up timer3 for audio interrupt
    cli();
	////	ASSR = 0b00100000;



    TCCR3A = 0b00000000;
    TCCR3B = 0b00000001;

    TIMSK3 |= _BV(OCIE3A);
	OCR3A = 100;
    sei();

	
//------------ End Audio shit ----------------

//------------ Start LED shit ----------------

  	TCCR0A = 0b00100011;
  	TCCR0B = 0b00000010;
  	TCCR1A = 0b10101001;
	TCCR1B = 0b00001010;

//------------ End LED shit ----------------
}

void blinkBlue(void){
    sbi(LEDB_PORT,LEDB_PINNUM);
    _delay_ms(100);
    cbi(LEDB_PORT,LEDB_PINNUM);
    _delay_ms(100);
}

void blinkGreen(void){
    sbi(LEDG_PORT,LEDG_PINNUM);
    _delay_ms(200);
    cbi(LEDG_PORT,LEDG_PINNUM);
    _delay_ms(200);
}

void blinkRed(void){
    sbi(LEDR_PORT,LEDR_PINNUM);
    _delay_ms(200);
    cbi(LEDR_PORT,LEDR_PINNUM);
    _delay_ms(200);
}

void IrLedOn()
{
	sbi(IRLED_PORT,IRLED_PINNUM);
}

void IrLedOff()
{
	cbi(IRLED_PORT,IRLED_PINNUM);
}

void InitADC(void){
   ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | IRT_ADC;
   ADCSRA = (1 << ADEN) | (0 << ADATE) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

   	//First conversion takes time so we do it here
	sbi(ADCSRA, ADSC);
	while (ADCSRA & (1<<ADSC));
}

void getADC(uint16_t *val){
	static uint8_t high,low;

	sbi(ADCSRA, ADSC);

	while (ADCSRA & (1<<ADSC));

	low = ADCL;
	high = ADCH;

	*val = ((uint16_t) high << 8) | low;
}

void testIR() {

	uint16_t i,result = 0, th = 7;
	IrLedOn();

	while(1) {

        getADC(&result);
		if (result > th) {
			DebugLedHi();
		}
		else {
			DebugLedLo();
		}
	}
}


